package com.example.yijian.edit.view.popup;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yijian.R;
import com.example.yijian.edit.clipEdit.correctionColor.ColorTypeAdapter;
import com.example.yijian.edit.clipEdit.correctionColor.ColorTypeItem;
import com.example.yijian.utils.Constants;
import com.example.yijian.utils.OnSeekBarChangeListenerAbs;
import com.example.yijian.utils.datainfo.ClipInfo;
import com.meicam.sdk.NvsVideoClip;
import com.meicam.sdk.NvsVideoFx;

import java.util.ArrayList;
import java.util.List;

public class AdjustPopup extends BaseCommonPopupWindow {
    private LinearLayout llSeek;
    private TextView tvReset;
    private SeekBar colorSeekBar;
    private RecyclerView rvColorType;
    private ImageView ivFinish;

    private ColorTypeAdapter mColorTypeAdapter;

    private String[] nameFxArray;
    private String mCurrentColorType;
    private NvsVideoFx mColorVideoFx, mVignetteVideoFx, mSharpenVideoFx, mTintVideoFx, mDenoiseVideoFx, mCurrentVideoFx;
    private ColorTypeItem mCurrentAdjustItem;

    private OnFunctionListener onFunctionListener;

    public AdjustPopup(Context context) {
        super(context);
        setContentView(R.layout.popup_adjust);
        initView();
        colorSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListenerAbs() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    float colorVal = getFloatColorVal(progress, mCurrentColorType);
                    if (onFunctionListener != null) {
                        onFunctionListener.onSeekChanged(colorVal, mCurrentColorType);
                    }
                }
            }
        });
        tvReset.setOnClickListener(v -> {
            int progress = getProgressByValue(mCurrentAdjustItem.getDefaultValue(), mCurrentColorType);
            //调节杆不是同一个 分别设置
            //The adjustment levers are not the same, set separately
            colorSeekBar.setProgress(progress);
            if (onFunctionListener != null) {
                onFunctionListener.onSeekChanged(mCurrentAdjustItem.getDefaultValue(), mCurrentColorType);
            }
        });
        ivFinish.setOnClickListener(v -> dismiss());
    }

    @Override
    public void onDismiss() {
        super.onDismiss();
        llSeek.setVisibility(View.GONE);

    }

    private void initView() {
        llSeek = findViewById(R.id.ll_seek);
        tvReset = findViewById(R.id.colorResetImageView);
        colorSeekBar = findViewById(R.id.colorSeekBar);
        rvColorType = findViewById(R.id.colorTypeRv);
        ivFinish = findViewById(R.id.iv_adjust_finish);
    }

    public void setData(ClipInfo clipInfo, NvsVideoClip videoClip) {
        initColorAdjustVideoFx(videoClip);
        nameFxArray = new String[]{
                Constants.ADJUST_BRIGHTNESS,
                Constants.ADJUST_CONTRAST,
                Constants.ADJUST_SATURATION,
                Constants.ADJUST_HIGHTLIGHT,
                Constants.ADJUST_SHADOW,
                Constants.ADJUST_TEMPERATURE,
                Constants.ADJUST_TINT,
                Constants.ADJUST_FADE,
                Constants.ADJUST_DEGREE,
                Constants.ADJUST_AMOUNT,
                Constants.ADJUST_DENOISE};
        List<ColorTypeItem> colorTypeItems = new ArrayList<>();

        TypedArray typedArray = getContext().getResources().obtainTypedArray(R.array.sub_adjust_menu_icon);
        TypedArray typedArraySelected = getContext().getResources().obtainTypedArray(R.array.sub_adjust_menu_icon_selected);
        String[] nameArray = getContext().getResources().getStringArray(R.array.adjust_menu_array);
        for (int index = 0; index < nameArray.length; index++) {
            ColorTypeItem menuInfo = new ColorTypeItem();
            menuInfo.setColorAtrubuteText(nameArray[index]);
            menuInfo.setColorTypeName(nameFxArray[index]);
            menuInfo.setIcon(typedArray.getResourceId(index, -1));
            menuInfo.setSelectedIcon(typedArraySelected.getResourceId(index, -1));
            if (index < 5 || index == 7) {
                menuInfo.setFxName(Constants.ADJUST_TYPE_BASIC_IMAGE_ADJUST);
            } else if (index == 9) {
                menuInfo.setFxName(Constants.ADJUST_TYPE_SHARPEN);

            } else if (index == 5 || index == 6) {
                menuInfo.setFxName(Constants.ADJUST_TYPE_TINT);

            } else if (index == 8) {
                menuInfo.setFxName(Constants.ADJUST_TYPE_VIGETTE);
            } else {
                menuInfo.setFxName(Constants.ADJUST_TYPE_DENOISE);
            }

            colorTypeItems.add(menuInfo);
        }
        typedArray.recycle();
        typedArraySelected.recycle();
        colorTypeItems.get(0).setSelected(true);
        mCurrentVideoFx = mColorVideoFx;
        mCurrentColorType = Constants.ADJUST_BRIGHTNESS;
        mCurrentAdjustItem = colorTypeItems.get(0);
        //获取亮度 对比度 饱和度 高光 阴影 褪色
        //Get brightness, contrast, saturation, highlight, shadow, fade
        float brightVal = (float) clipInfo.getBrightnessVal();
        float contrastVal = (float) clipInfo.getContrastVal();
        float saturationVal = (float) clipInfo.getSaturationVal();
        float highLight = (float) clipInfo.getmHighLight();
        float shadow = (float) clipInfo.getmShadow();
        float fade = (float) clipInfo.getFade();
        //暗角
        float vignette = (float) clipInfo.getVignetteVal();
        //获取锐度
        float sharpen = (float) clipInfo.getSharpenVal();
        //获取色温 色调
        float temperature = (float) clipInfo.getTemperature();
        float tint = (float) clipInfo.getTint();
        //噪点
        float intensity = (float) clipInfo.getDensity();
        //噪点密度
        float density = (float) clipInfo.getDenoiseDensity();
        //设置默认值（此值为进入页面带有的值 重置的原点）
        //Set the default value (this value is the value that enters the page with the reset origin)
        //特殊标注 这里 的顺序是按照显示的功能排列
        //Special labels The order here is arranged according to the displayed function
        colorTypeItems.get(0).setDefaultValue(brightVal);
        colorTypeItems.get(1).setDefaultValue(contrastVal);
        colorTypeItems.get(2).setDefaultValue(saturationVal);
        colorTypeItems.get(3).setDefaultValue(highLight);
        colorTypeItems.get(4).setDefaultValue(shadow);
        colorTypeItems.get(5).setDefaultValue(temperature);
        colorTypeItems.get(6).setDefaultValue(tint);
        colorTypeItems.get(7).setDefaultValue(fade);
        colorTypeItems.get(8).setDefaultValue(vignette);
        colorTypeItems.get(9).setDefaultValue(sharpen);
        //设置噪点的程度和密度 Set the level and density of noise
//        colorTypeItems.get(10).setDefaultValue(intensity);
//        colorTypeItems.get(10).setExtra(density);

        mColorTypeAdapter = new ColorTypeAdapter(getContext(), colorTypeItems);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rvColorType.setLayoutManager(linearLayoutManager);
        rvColorType.setAdapter(mColorTypeAdapter);

        mColorTypeAdapter.setOnItemClickListener(new ColorTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, ColorTypeItem colorTypeItem) {
                if (colorTypeItem == null || colorTypeItem.getColorTypeName() == null || colorTypeItem.getFxName() == null) {
                    return;
                }
                mCurrentAdjustItem = colorTypeItem;
                llSeek.setVisibility(View.VISIBLE);
                /*
                 * 校色参数
                 * Calibration parameters
                 * 设置当前的特效对象
                 * */
                //当选择的是噪点选项时，默认选择的单色模式,类型设置的是噪点强度调节，需要在调节滑竿是在赋值
                mCurrentColorType = colorTypeItem.getColorTypeName();

                if (colorTypeItem.getFxName().equals(Constants.ADJUST_TYPE_BASIC_IMAGE_ADJUST)) {
                    mCurrentVideoFx = mColorVideoFx;
                } else if (colorTypeItem.getFxName().equals(Constants.ADJUST_TYPE_VIGETTE)) {
                    mCurrentVideoFx = mVignetteVideoFx;
                } else if (colorTypeItem.getFxName().equals(Constants.ADJUST_TYPE_SHARPEN)) {
                    mCurrentVideoFx = mSharpenVideoFx;
                } else if (colorTypeItem.getFxName().equals(Constants.ADJUST_TYPE_TINT)) {
                    mCurrentVideoFx = mTintVideoFx;
                }
                //设置进度
                colorSeekBar.setProgress(getProgressByValue((float) mCurrentVideoFx.getFloatVal(mCurrentColorType), mCurrentColorType));
            }
        });
    }

    /**
     * 获取当前设置的特效和值
     * Get the currently set special effect and value
     */
    private void initColorAdjustVideoFx(NvsVideoClip videoClip) {
        if (videoClip == null) {
            return;
        }
        int fxCount = videoClip.getFxCount();
        for (int index = 0; index < fxCount; ++index) {
            NvsVideoFx videoFx = videoClip.getFxByIndex(index);
            if (videoFx == null) {
                continue;
            }

            String fxName = videoFx.getBuiltinVideoFxName();
            if (fxName == null || TextUtils.isEmpty(fxName)) {
                continue;
            }
            if (fxName.equals(Constants.ADJUST_TYPE_BASIC_IMAGE_ADJUST)) {
                mColorVideoFx = videoFx;
            } else if (fxName.equals(Constants.ADJUST_TYPE_VIGETTE)) {
                mVignetteVideoFx = videoFx;
            } else if (fxName.equals(Constants.ADJUST_TYPE_SHARPEN)) {
                mSharpenVideoFx = videoFx;
            } else if (fxName.equals(Constants.ADJUST_TYPE_TINT)) {
                mTintVideoFx = videoFx;
            } else if (fxName.equals(Constants.ADJUST_TYPE_DENOISE)) {
                mDenoiseVideoFx = videoFx;
            }
        }

        if (mColorVideoFx == null) {
            mColorVideoFx = videoClip.appendBuiltinFx(Constants.ADJUST_TYPE_BASIC_IMAGE_ADJUST);
            mColorVideoFx.setAttachment(Constants.ADJUST_TYPE_BASIC_IMAGE_ADJUST, Constants.ADJUST_TYPE_BASIC_IMAGE_ADJUST);
        }

        if (mVignetteVideoFx == null) {
            mVignetteVideoFx = videoClip.appendBuiltinFx(Constants.ADJUST_TYPE_VIGETTE);
            mVignetteVideoFx.setAttachment(Constants.ADJUST_TYPE_VIGETTE, Constants.ADJUST_TYPE_VIGETTE);
        }

        if (mSharpenVideoFx == null) {
            mSharpenVideoFx = videoClip.appendBuiltinFx(Constants.ADJUST_TYPE_SHARPEN);
            mSharpenVideoFx.setAttachment(Constants.ADJUST_TYPE_SHARPEN, Constants.ADJUST_TYPE_SHARPEN);
        }

        if (mTintVideoFx == null) {
            mTintVideoFx = videoClip.appendBuiltinFx(Constants.ADJUST_TYPE_TINT);
            mTintVideoFx.setAttachment(Constants.ADJUST_TYPE_TINT, Constants.ADJUST_TYPE_TINT);
        }


        if (null == mDenoiseVideoFx) {
            mDenoiseVideoFx = videoClip.appendBuiltinFx(Constants.ADJUST_TYPE_DENOISE);
            mDenoiseVideoFx.setAttachment(Constants.ADJUST_TYPE_DENOISE, Constants.ADJUST_TYPE_DENOISE);
        }

    }


    /**
     * 通过当前的进度 获取对应设置特效的值
     * Obtain the value of the corresponding special effect through the current progress
     *
     * @param progress
     * @param mCurrentColorType
     * @return
     */
    private float getFloatColorVal(int progress, String mCurrentColorType) {
        if (!TextUtils.isEmpty(mCurrentColorType)) {
            //暗角 噪点取值 0 -1
            if (mCurrentColorType.equals(Constants.ADJUST_DEGREE) || mCurrentColorType.equals(Constants.ADJUST_DENOISE) || mCurrentColorType.equals(Constants.ADJUST_DENOISE_DENSITY)) {
                return progress / 100f;
            }
            //锐度 0 - 5
            else if (mCurrentColorType.equals(Constants.ADJUST_AMOUNT)) {
                return progress / 100f * 5;
            }
            //褪色 0 ~ -10
            else if (mCurrentColorType.equals(Constants.ADJUST_FADE)) {
                return -progress / 100f * 10;
            } else {
                //其他 -1 ~ 1
                return progress / 50f - 1;

            }
        }
        return progress / 50f - 1;
    }

    /**
     * 通过特效的值获取对应的进度是多少
     * Get the corresponding progress through the value of the special effect
     *
     * @param value
     * @param mCurrentColorType
     * @return
     */
    private int getProgressByValue(float value, String mCurrentColorType) {
        if (!TextUtils.isEmpty(mCurrentColorType)) {
            //暗角 取值 0 -1
            if (mCurrentColorType.equals(Constants.ADJUST_DEGREE) || mCurrentColorType.equals(Constants.ADJUST_DENOISE) || mCurrentColorType.equals(Constants.ADJUST_DENOISE_DENSITY)) {
                return (int) (value * 100);
            }
            //锐度取值 0 - 5
            else if (mCurrentColorType.equals(Constants.ADJUST_AMOUNT)) {
                return (int) (value * 100 / 5);
            }
            //褪色0 ~ -10
            else if (mCurrentColorType.equals(Constants.ADJUST_FADE)) {
                return -(int) (value * 100f / 10);
            } else {
                return (int) (value * 50 + 50);
            }
        }
        return (int) (value * 50 + 50);
    }

    public void setOnFunctionListener(OnFunctionListener callBack) {
        this.onFunctionListener = callBack;
    }


    public interface OnFunctionListener {
        void onSeekChanged(float colorVal, String mCurrentColorType);
    }

}
